package cn.com.generaldata.os.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

public class CommonUtil {

	/**
	 * 创建NG的消息.
	 * 
	 * @param msg
	 *            消息文字.
	 * @return
	 */
	public static Map<String, String> createNGMsg(String msg) {
		Map<String, String> m = new HashMap<String, String>();
		m.put("result", "NG");
		m.put("message", msg);
		return m;
	}

	/**
	 * 创建OK的消息.
	 * 
	 * @param msg
	 *            消息文字.
	 * @return
	 */
	public static Map<String, String> createOKMsg(String msg) {
		Map<String, String> m = new HashMap<String, String>();
		m.put("result", "OK");
		m.put("message", msg);
		return m;
	}

	/**
	 * 下载文件.
	 * 
	 * @param filePath
	 *            文件路径
	 * @param fileName
	 *            下载显示文件名
	 * @throws IOException
	 */
	public static void downloadFile(String filePath, String fileName, HttpServletResponse response) {

		// 文件读到流中
		InputStream in = null;
		try {
			in = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}

		// 输出到response
		OutputStream out = null;
		try {
			out = response.getOutputStream();

			// 文件名编码
			String encodeFileName = getEncodeFileName(fileName);

			// 设置输出的格式
			response.reset();
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + encodeFileName + "\";filename*=utf-8''" + encodeFileName);

			// 循环取出流中的数据
			byte[] b = new byte[64 * 1024];
			int len;
			while ((len = in.read(b)) > 0) {
				out.write(b, 0, len);
				out.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 对文件名进行编码，下载时使用.
	 * 
	 * @param fileName
	 *            文件名
	 * @return 编码后文件名
	 */
	private static String getEncodeFileName(String fileName) {
		if (fileName == null || fileName.length() == 0) {
			return fileName;
		}

		// 文件名进行UTF-8的URLEncode
		try {
			// abc.jpg
			int dotIndex = fileName.lastIndexOf(".");

			// 文件名不包含“.”
			if (dotIndex == -1) {
				return URLEncoder.encode(fileName, "utf-8");
			}

			// 文件名包含“.”
			String name = fileName.substring(0, dotIndex); // abc
			String suffix = fileName.substring(dotIndex); // .jpg
			return URLEncoder.encode(name, "utf-8") + suffix;
		} catch (UnsupportedEncodingException e) {
			return fileName;
		}
	}

	public static void main(String[] args) {
		System.out.println(getEncodeFileName("Hello嘎嘎123.jpg"));
		System.out.println(getEncodeFileName("Hello嘎嘎123"));
	}
}
